package grpc

import (
	"fmt"
	"gitee.com/dreamwood/ez"
	"os/exec"
)

var root string

func CreateProto(c *Server) {
	content := twigger.Render("/grpc/proto.twig", c)

	path := fmt.Sprintf("%s/grpc/%s.proto", root, c.Name)
	ez.CreateFile(path, []byte(content))
	//生成相应的文件
	cmd := exec.Command("protoc",
		fmt.Sprintf("--go_out=./grpc"),
		fmt.Sprintf("--go-grpc_out=./grpc"),
		fmt.Sprintf("./grpc/%s.proto", c.Name),
	)
	e := cmd.Run()
	ez.PrintInfo(cmd.String())
	ez.PrintError(e)
	CreateProtoBatFile(c, fmt.Sprintf("protoc.exe --go_out=./ --go-grpc_out=./ ./%s.proto", c.Name))
}

// 创建最初的Server文件
func CreateServerFile(c *Server, targetProject ...string) {
	content := twigger.Render("/grpc/server.twig", c)
	path := fmt.Sprintf("%s/app/%s/grpc/server/%sServer.go", root, ez.Lcfirst(c.Name), c.Name)
	ez.CreateDirForPath(path)
	ez.CreateFile(path, []byte(content))
	//if len(targetProject) > 0 {
	//	for _, dir := range targetProject {
	//		path := fmt.Sprintf("%s/app/%s/grpc/server/%s.go", root, dir, c.Name)
	//		ez.CreateDirForPath(path)
	//		ez.CreateFile(path, []byte(content))
	//	}
	//}

}

// 创建最初的Client文件
func CreateClientFile(c *Server, targetProject ...string) {
	content := twigger.Render("/grpc/client.twig", c)
	//path := fmt.Sprintf(
	//	"%s/app/%s/grpc/client/%s.go",
	//	root, ez.Lcfirst(c.Name), c.Name)
	//ez.CreateDirForPath(path)
	//ez.CreateFile(path, []byte(content))

	if len(targetProject) > 0 {
		for _, dir := range targetProject {
			path := fmt.Sprintf(
				"%s/app/%s/grpc/client/%sClient.go",
				root, dir, c.Name)
			ez.CreateDirForPath(path)
			ez.CreateFile(path, []byte(content))
		}
	}
}

// 创建最初的Client文件
func CreateProtoBatFile(c *Server, cmd string) {
	path := fmt.Sprintf("%s/grpc/%s.bat", root, c.Name)
	ez.CreateFile(path, []byte(cmd))
}
